package com.crl.rcdp.monitor.service;

import com.cars.util.jwt.JwtUtil;
import com.cars.util.list.ListUtils;
import com.crl.rcdp.sys.dao.SysUserDao;
import com.crl.rcdp.sys.dto.SysUserDTO;
import com.crl.rcdp.sys.model.SysUser;
import com.crl.rcdp.sys.vo.SysUserSearchVO;
import com.crl.redis.RedisKey;
import com.crl.redis.RedisUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

/**
 * @description:
 * @author: 孔垂云
 * @version: 1.0
 * @date: 2020/7/8 13:57
 */
@Service
public class MonitorOnlineService {
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private SysUserDao sysUserDao;

    /**
     * 在线用户
     *
     * @return
     */
    public List<SysUserDTO> listOnline2() {
        Set<String> keys = redisUtil.like(RedisKey.AUTHORIZATION_KEY);
        List<SysUserDTO> list = new ArrayList<>();
        Iterator<String> it = keys.iterator();
        while (it.hasNext()) {
            String str = it.next();
            String token = redisUtil.get(str, String.class); //获取每个token
            //根据token获取userid
            int userId = JwtUtil.getUserId(token);
            SysUser sysUser = sysUserDao.get(userId);
            if (sysUser != null) {
                SysUserDTO sysUserDTO = new SysUserDTO();
                BeanUtils.copyProperties(sysUser, sysUserDTO);
                list.add(sysUserDTO);
            }
        }
        return list;
    }

    /**
     * 在线用户
     *
     * @param sysUserSearchVO
     * @return
     */
    public List<SysUserDTO> listOnline(SysUserSearchVO sysUserSearchVO) {
        //根据最后登录时间判断在线用户，最后登录时间距当前时间<2小时的即为在线。
        List<SysUserDTO> list = new ArrayList<>();
        List<SysUser> listOnline = sysUserDao.listOnline(120, sysUserSearchVO);//
        list = ListUtils.copyList(listOnline, SysUserDTO.class);
        return list;
    }

    /**
     * 在线人数合计
     *
     * @param sysUserSearchVO
     * @return
     */
    public int listOnlineCount(SysUserSearchVO sysUserSearchVO) {
        //根据最后登录时间判断在线用户，最后登录时间距当前时间<2小时的即为在线。
        return sysUserDao.listOnlineCount(120, sysUserSearchVO);//
    }

    /**
     * 强制下线
     *
     * @param sysUserSearchVO
     */
    public void logout(SysUserSearchVO sysUserSearchVO) {
        //删除对应的token
        redisUtil.del(RedisKey.AUTH_PASSWORD_KEY + sysUserSearchVO.getUsername());
    }
}
